package yc.star.friend.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yc.star.api.RemoteJudgeService;
import yc.star.api.domain.UserExeResult;
import yc.star.api.domain.dto.JudgeSubmitDTO;
import yc.star.api.domain.vo.UserQuestionResultVO;
import yc.star.common.constants.Constant;
import yc.star.common.domain.AppResult;
import yc.star.common.enums.ProgramType;
import yc.star.common.enums.QuestionResType;
import yc.star.common.security.exception.ApplicationException;
import yc.star.common.utils.ThreadLocalUtil;
import yc.star.friend.domain.question.Question;
import yc.star.friend.domain.question.QuestionCase;
import yc.star.friend.domain.question.es.QuestionES;
import yc.star.friend.domain.user.UserSubmit;
import yc.star.friend.domain.user.dto.UserSubmitDTO;
import yc.star.friend.elasticsearch.QuestionRepository;
import yc.star.friend.mapper.QuestionMapper;
import yc.star.friend.mapper.UserSubmitMapper;
import yc.star.friend.rabbit.JudgeProducer;
import yc.star.friend.service.IUserQuestionService;

import java.util.List;


@Service
public class UserQuestionServiceImpl implements IUserQuestionService {

    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private RemoteJudgeService remoteJudgeService;
    @Autowired
    private JudgeProducer judgeProducer;
    @Autowired
    private UserSubmitMapper userSubmitMapper;


    @Override
    public AppResult<UserQuestionResultVO> submit(UserSubmitDTO submitDTO) {
        Integer programType = submitDTO.getProgramType();
        if (ProgramType.JAVA.getValue().equals(programType)) {
            // 语言类型为JAVA
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(submitDTO);
            // 调用判题服务进行判题
            return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);
        }
        throw new ApplicationException(AppResult.failed("该系统暂不支持其他语言类型"));
    }

    @Override
    public boolean rabbitSubmit(UserSubmitDTO submitDTO) {
        Integer programType = submitDTO.getProgramType();
        if (ProgramType.JAVA.getValue().equals(programType)) {
            //按照java逻辑处理
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(submitDTO);
            judgeProducer.produceMsg(judgeSubmitDTO);
            return true;
        }
        throw new ApplicationException(AppResult.failed("提交代码失败"));
    }

    @Override
    public UserQuestionResultVO exeResult(Long examId, Long questionId, String currentTime) {
        Long userId = ThreadLocalUtil.get(Constant.USER_ID, Long.class);
        UserSubmit userSubmit = userSubmitMapper.selectCurrentUserSubmit(userId, examId, questionId, currentTime);
        UserQuestionResultVO resultVO = new UserQuestionResultVO();
        if (userSubmit == null) {
            resultVO.setPass(QuestionResType.IN_JUDGE.getValue());
        } else {
            resultVO.setPass(userSubmit.getPass());
            resultVO.setExeMessage(userSubmit.getExeMessage());
            if (StrUtil.isNotEmpty(userSubmit.getCaseJudgeRes())) {
                resultVO.setUserExeResultList(JSON.parseArray(userSubmit.getCaseJudgeRes(), UserExeResult.class));
            }
        }
        return resultVO;
    }

    private JudgeSubmitDTO assembleJudgeSubmitDTO(UserSubmitDTO submitDTO) {
        // 拿到题目id
        Long questionId = submitDTO.getQuestionId();
        // 在ES中查出该题目的详细信息
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        JudgeSubmitDTO judgeSubmitDTO = new JudgeSubmitDTO();
        if (questionES != null) {
            // 拼装judgeSubmitDTO
            BeanUtil.copyProperties(questionES,judgeSubmitDTO);
        } else {
            // ES中不存在该题目,将数据库中的数据同步
            Question question = questionMapper.selectById(questionId);
            BeanUtil.copyProperties(question,judgeSubmitDTO);
            // 同步ES
            questionES = new QuestionES();
            BeanUtil.copyProperties(question,questionES);
            questionRepository.save(questionES);
        }
        // 拼接完整的拼装judgeSubmitDTO
        judgeSubmitDTO.setUserId(ThreadLocalUtil.get(Constant.USER_ID, Long.class));
        judgeSubmitDTO.setExamId(submitDTO.getExamId());
        judgeSubmitDTO.setProgramType(submitDTO.getProgramType());
        // 拼装整个代码体
        judgeSubmitDTO.setUserCode(codeConnect(submitDTO.getUserCode(),questionES.getMainFuc()));
        // 将输入和输出结果反序列化
        List<QuestionCase> questionCaseList = JSONUtil.toList(questionES.getQuestionCase(), QuestionCase.class);
        List<String> inputList = questionCaseList.stream().map(QuestionCase::getInput).toList();
        judgeSubmitDTO.setInputList(inputList);
        List<String> outputList = questionCaseList.stream().map(QuestionCase::getOutput).toList();
        judgeSubmitDTO.setOutputList(outputList);
        return judgeSubmitDTO;
    }

    private String codeConnect(String userCode, String mainFunc) {
        String targetCharacter = "}";
        int targetLastIndex = userCode.lastIndexOf(targetCharacter);
        if (targetLastIndex != -1) {
            return userCode.substring(0, targetLastIndex) + "\n" + mainFunc + "\n" + userCode.substring(targetLastIndex);
        }
        throw new ApplicationException(AppResult.failed("操作失败"));
    }

}